package com.shadowtorcher.stdisk.listener;

import com.shadowtorcher.soulknife.SoulKnifeDB;
import com.shadowtorcher.soulknife.exception.BeanConfigErrorException;
import com.shadowtorcher.stdisk.bean.LogicFileBean;
import com.shadowtorcher.stdisk.bean.UserBean;
import com.shadowtorcher.stdisk.logic.FileDeleter;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

@WebListener()
public class AutoDeleteListener implements ServletContextListener,
        HttpSessionListener, HttpSessionAttributeListener {
    private Timer timer = null;

    public AutoDeleteListener() {
    }

    public void contextInitialized(ServletContextEvent sce) {
        timer = new Timer(true);
        timer.schedule(new DeleteTimer(), 0, 24 * 60 * 60 * 1000);
        // 每天运行一次
    }

    public void contextDestroyed(ServletContextEvent sce) {
        timer.cancel();
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {

    }


    private static class DeleteTimer extends TimerTask {
        private void delete() {
            try {
                List<LogicFileBean> list = SoulKnifeDB.selectWhere("LogicPath  like ?", "bin/%").setClass(LogicFileBean.class);
                for (LogicFileBean file : list) {
                    UserBean user = SoulKnifeDB.selectWhere("UserID = ?", file.getUserID()).setClass(UserBean.class).get(0);
                    FileDeleter deleter = new FileDeleter(file, user);
                    Date now = new Date();
                    long time = 604800; // 7 * 24 * 60 * 60 一周;
                    if (now.getTime() > file.getModifiDate().getTime() + time) {
                        deleter.doDelete();
                    }
                }
            } catch (SQLException | BeanConfigErrorException e) {
                e.printStackTrace();
            }
        }

        public void run() {
            delete();
        }

    }
}
